﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace Commerce.CSK.Web.Controls
{

    public class ProductAddedToCartEventArgs : EventArgs
    {
        public ProductAddedToCartEventArgs(Commerce.Data.Product addedProduct)
        {
            _product = addedProduct;
        }

        Commerce.Data.Product _product;
        public Commerce.Data.Product AddedProduct
        {
            get { return _product; }
        }
    }

    public partial class ProductDisplay : ItemViewControl
    {
        public event EventHandler<ProductAddedToCartEventArgs> ProductAddedToCart;

        public ProductDisplay()
        {
            this.ShowDescription = true;
            this.ShowAddToCart = true;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            this.descriptionLabel.Visible = ShowDescription;
            this.addToCartPanel.Visible = ShowAddToCart;
        }
        private Commerce.Data.Product _selectedProduct;
        public Commerce.Data.Product SelectedProduct
        {
            get
            {
                if (_selectedProduct == null)
                {
                    //Check for the id. 
                    int? productId = ItemId;
                    if (productId != null && productId.HasValue)
                    {
                        _selectedProduct = Services.GetCatalogService().GetProduct(productId.Value);
                    }
                }
                return _selectedProduct;
            }
            set
            {
                _selectedProduct = value;
                if (value != null)
                {
                    ItemId = _selectedProduct.ID;
                }
                else
                {
                    ItemId = null;
                }
            }
        }

        [DefaultValue(true)]
        [Category("Appearance")]
        public bool ShowDescription { get; set; }

        [Category("Appearance")]
        [DefaultValue(true)]
        public bool ShowAddToCart { get; set; }


        protected void addToCart_Click(object sender, EventArgs e)
        {
            Services.AddProductToCart(this.SelectedProduct); 
            OnProductAddedToCart(this.SelectedProduct);
        }

        protected virtual void OnProductAddedToCart(Commerce.Data.Product addedProduct)
        {
            if (ProductAddedToCart != null)
            {
                ProductAddedToCart(this, new ProductAddedToCartEventArgs(addedProduct));
            }
        }

    }
}